﻿using Account.Api.Services.Mapping;
using AspectCore.Extensions.Autofac;
using Autofac;
using Cyss.Core;
using Cyss.Core.Api;
using Cyss.Core.Api.Client;
using Cyss.Core.Api.Models;
using Cyss.Core.Cache;
using Cyss.Core.Helper;
using Cyss.Core.Infrastructure;
using Cyss.Core.Repository;
using Cyss.Core.Repository.EF;
using Microsoft.EntityFrameworkCore;

namespace Account.Api.Infrastructure
{

    /// <summary>
    /// IOC 注册
    /// </summary>
    public class DependencyRegistrar : IDependencyRegistrar
    {
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        public void Register(ContainerBuilder builder)
        {

            builder.Register(c =>
            {
                var optionsBuilder = new DbContextOptionsBuilder<UserObjectContext>();
                optionsBuilder.UseSqlServer(IOCEngine.Resolve<AccountConnectionString>().Value);
                return optionsBuilder.Options;
            }).InstancePerLifetimeScope();

            builder.Register(context => new UserObjectContext(context.Resolve<DbContextOptions<UserObjectContext>>()))
                   .As<IDbContext>().InstancePerLifetimeScope();

            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

            builder.RegisterType<ApiToken>().As<IApiToken>().SingleInstance();

            builder.RegisterAllService();

            builder.RegisterType<DefaultLogging>().As<ILogging>().SingleInstance();
            builder.RegisterType<DefaultClientLogging>().As<IClientLogging>().SingleInstance();
            builder.RegisterType<DefaultRequestLogging>().As<IRequestLogging>().SingleInstance();

            builder.RegisterDynamicProxy();

            var controllerBaseType = typeof(AccountBaseApiController);
            builder.RegisterAssemblyTypes(typeof(Program).Assembly)
                .Where(x => controllerBaseType.IsAssignableFrom(x) && x != controllerBaseType).PropertiesAutowired();


        }



    }
}
